<template>
    <div>
        <Row>
            <i-col span="8">
                <div class="mb-2">
                    <span v-show="!titleEdit.on">{{title}}</span>

                    <Input clearable v-show="titleEdit.on" type="text" v-model="title" style="width:100px;" />
                    
                    <Button 
                    v-show="titleEdit.on" 
                    icon="checkmark-round" 
                    class="ml-1 unfocus" 
                    shape="circle" 
                    size="small" 
                    type="text" 
                    @click="titleEdit.send(updateTitle)"
                    :loading="titleEdit.loading">
                    </Button>

                    <Button 
                    v-show="!titleEdit.on" 
                    icon="edit" 
                    class="ml-1" 
                    shape="circle" 
                    size="small" 
                    type="text" @click="titleEdit.switch()"></Button>
                </div>

                <Collapse class="mr-2 mb-2" v-for="(apiCard,$index) in apiCardList" :key="apiCard.oid" :value="apiCard.oid+''" :class="apiCard.indentClass" @on-change="v=>{loadApiCardTree(apiCard)}" accordion>
                    <Panel :name="apiCardList[0].oid+''">
                        <span v-show="!apiCard.editer.on" class="ml-1">{{apiCard.aliasName}}</span>

                        <Input clearable @on-click.stop.prevent="headerFocusFn" v-show="apiCard.editer.on" type="text" v-model="apiCard.aliasName" style="width:100px;" />

                        <div style="float:right;">
                            <Button v-if="apiCard.isBase" @click.stop="searchCard" icon="search" shape="circle" size="small" type="text"></Button>
                            <Button 
                            v-show="apiCard.editer.on" 
                            icon="checkmark-round" 
                            class="ml-1 unfocus" 
                            shape="circle" 
                            size="small" 
                            type="text" 
                            @click.stop="updateAliasName(apiCard,$index)"
                            :loading="titleEdit.loading">
                            </Button>
                            <Button icon="edit" v-show="!apiCard.editer.on" @click.stop="openAliasNameEdit(apiCard,$index)" shape="circle" size="small" type="text" class="unfocus"></Button>
                            <Button icon="merge" @click.stop="addCard(apiCard.oid)" shape="circle" size="small" type="text"></Button>
                            <Button v-if="apiCard.isBase" @click.stop="allCardTouch" v-bind:icon="allCardState" shape="circle" size="small" type="text"></Button>
                            <Button v-if="!apiCard.isBase" @click.stop="removeCard(apiCard)" icon="trash-b" shape="circle" size="small" type="text"></Button>
                        </div>
                        <div slot="content">
                            <v-jstree v-show="apiCard.treeDataList.length > 0" :data="apiCard.treeDataList" :class="{ 'tree-rtl': isRTL }" allow-batch @item-click="itemClick" />
                            <small class="text-muted" v-show="apiCard.treeDataList.length == 0">暂无数据</small>
                        </div>
                    </Panel>
                </Collapse>
            </i-col>
            <i-col span="14">

                <Tabs type="card" class="mr-2" v-model="activeTab">
                    <TabPane label="节点编辑" icon="hammer" name="workspace">
                        <b-card no-body>
                            <b-card-header>
                                <strong v-show="!nodeTitleEdit.on"> {{decideWorkspace.name}}</strong>
                                <Input clearable v-show="nodeTitleEdit.on" type="text" v-model="decideWorkspace.name" style="width:100px;" />

                                <Button 
                                v-show="nodeTitleEdit.on" 
                                icon="checkmark-round" 
                                class="ml-1 unfocus" 
                                shape="circle" 
                                size="small" 
                                type="text" 
                                @click="nodeTitleEdit.send(updateTitle)"
                                :loading="nodeTitleEdit.loading">
                                </Button>

                                <Button 
                                v-show="!nodeTitleEdit.on" 
                                icon="edit" 
                                class="ml-1" 
                                shape="circle" 
                                size="small" 
                                type="text" @click="nodeTitleEdit.switch()"></Button>
                            </b-card-header>
                            <b-card-body>
                                <div class="card-item mb-4">
                                    <span>已选择的数据对象：</span>
                                    <div class="tool-play mb-1" v-if="decideWorkspace.choiseTree">{{decideWorkspace.choiseTreeApiPath}}</div>
                                    <div v-if="!decideWorkspace.choiseTree">
                                        <small class="text-muted">(选择左侧任意节点)</small>
                                    </div>
                                    <span>已选择的数据对象的属性：</span>
                                    <div class="tool-play" v-if="decideWorkspace.choiseTree">{{decideWorkspace.choiseTree.pathName}}</div>
                                    <div v-if="!decideWorkspace.choiseTree">
                                        <small class="text-muted">(选择左侧任意节点)</small>
                                    </div>
                                </div>

                                <div class="card-item mb-4">
                                    <span>判断工具：
                                        <small class="text-muted" v-if="decideWorkspace.choiseTool">{{decideWorkspace.choiseTool.name}}</small>
                                        <small class="text-muted" v-else>(选择右侧判定工具)</small>
                                    </span>
                                    <component v-bind:is="toolComponentList[decideWorkspace.choiseTool.code]" :val="decideWorkspace.determinationData"></component>
                                </div>

                                <div class="card-item">
                                    <Tabs type="line">
                                        <TabPane icon="arrow-left-a" label="True" name="true">
                                            <Row>
                                                <i-col span="4">
                                                    <label style="line-height:32px;">处理动作：</label>
                                                </i-col>
                                                <i-col span="6">
                                                    <b-select v-model="decideWorkspace.trueAction.actionType" :options="actions" />
                                                </i-col>
                                            </Row>
                                            <Row v-show="decideWorkspace.trueAction.actionType === 'Action'">
                                                <i-col span="4">
                                                    <label style="line-height:32px;">事件级别：</label>
                                                </i-col>
                                                <i-col span="6">
                                                    <b-select v-model="decideWorkspace.trueAction.alertLevel" :options="alertLevelList" />
                                                </i-col>
                                            </Row>
                                            <Row class="mb-2" v-show="decideWorkspace.trueAction.actionType === 'Action'">
                                                <i-col span="4">
                                                    <label style="line-height:32px;">事件标题：</label>
                                                </i-col>
                                                <i-col span="18">
                                                    <Input type="textarea"  :rows="4" style="width:100%;" placeholder="消息标题" value="##runtime.Date##执行打分卡001得分##runtime.Result##,低于预警线300"></Input>
                                                </i-col>
                                            </Row>
                                        </TabPane>
                                        <TabPane icon="arrow-right-a" label="False" name="false">
                                            <Row>
                                                <i-col span="4">
                                                    <label style="line-height:32px;">处理动作：</label>
                                                </i-col>
                                                <i-col span="6">
                                                    <b-select v-model="decideWorkspace.falseAction.actionType" :options="actions" />
                                                </i-col>
                                            </Row>
                                            <Row v-show="decideWorkspace.falseAction.actionType === 'Action'">
                                                <i-col span="4">
                                                    <label style="line-height:32px;">事件级别：</label>
                                                </i-col>
                                                <i-col span="6">
                                                    <b-select v-model="decideWorkspace.falseAction.alertLevel" :options="alertLevelList" />
                                                </i-col>
                                            </Row>
                                            <Row class="mb-2" v-show="decideWorkspace.falseAction.actionType === 'Action'">
                                                <i-col span="4">
                                                    <label style="line-height:32px;">事件标题：</label>
                                                </i-col>
                                                <i-col span="18">
                                                    <Input type="textarea" :rows="4" style="width:100%;" placeholder="消息标题" value="##runtime.Date##执行打分卡001得分##runtime.Result##,低于预警线300"></Input>
                                                </i-col>
                                            </Row>
                                        </TabPane>
                                    </Tabs>
                                </div>
                            </b-card-body>
                            <b-card-footer class="text-muted small" v-show="(showTrueShortcut && decideWorkspace.trueAction.actionType === 'LinkNode') || (showFalseShortcut && decideWorkspace.falseAction.actionType === 'LinkNode')">
                                <indicator-shortcut actionType="true" v-show="decideWorkspace.trueAction.actionType === 'LinkNode'" label="True子判定快捷链接"></indicator-shortcut>
                                <indicator-shortcut actionType="false" v-show="decideWorkspace.falseAction.actionType === 'LinkNode'" label="False子判定快捷链接"></indicator-shortcut>
                            </b-card-footer>
                        </b-card>
                    </TabPane>
                    <TabPane label="节点视图" icon="android-map" name="view">
                        <div class="nodeMap" id="myDiagramDiv"></div>
                    </TabPane>
                </Tabs>

            </i-col>
            <i-col span="2">
                <b-card header="工具" header-tag="h6" class="mb-1 tool-item-container text-center">
                    <sky-tool-item v-for="tool in toolList" 
                    :key="tool.code" 
                    :code="tool.code"
                    :label="tool.name" 
                    :img="globalConst.DECIDE_TOOL_ICON_LIST[tool.code]+''"></sky-tool-item>
                    <small class="text-muted" v-show="toolList.length == 0">暂无数据</small>
                </b-card>
            </i-col>
        </Row>

        <!-- 节点视图 -->
        <Modal v-model="apiCardModal.show" title="选择下探数据接口" :mask-closable="false">
            <Table stripe border :columns="apiCardModal.table.columns" :data="apiCardModal.table.data"></Table>
        </Modal>
    </div>
</template>

<style src="@/vendor/libs/vue-data-tables/vue-data-tables.scss" lang="scss"></style>
<style src="@/vendor/libs/sweet-modal-vue/sweet-modal-vue.scss" lang="scss"></style>
<style src="@/vendor/libs/vue-jstree/vue-jstree.scss" lang="scss"></style>
<style scoped>
@keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
}

.nodeMap {
    height: 450px;
    width: 100%;
    margin: 0 auto;
    border: 1px solid #ccc;
    background-color: white;
}

.tool-item-container > div.card-body {
    padding: 4px;
}

.tool-play {
    border: 1px dashed gray;
    padding: 4px;
    text-align: left;
    background-color: whitesmoke;
}

div.ivu-collapse.ml-0 {
    border: 1px dashed #666;
}

.unfocus.ivu-btn:focus{
    box-shadow: none !important; 
}

</style>

<script>
import Vue from "vue";
import VJstree from "vue-jstree";
import ToolDengYu from "@/commComponents/toolComponents/Dengyu";
import ToolDateZaoYu from "@/commComponents/toolComponents/DateZaoYu";
import ToolStringContains from "@/commComponents/toolComponents/StringContains";
import ToolDaYu from "@/commComponents/toolComponents/DaYu";
import ScoreAction from "@/commComponents/ScoreAction";
import IndicatorShortcut from "@/commComponents/IndicatorShortcut";
import go from "gojs";
import CONST from "@/const";
import "@/assets/icons";

// 思维导图相关变量
var $ = go.GraphObject.make;
var myDiagram = null;

var bluegrad = "#2b85e4";
var pinkgrad = "#e780a3";
var graygrad = "#bbbec4";

// 文本编辑器原型对象
var TextEdit = function(){
    return {
        on: false,
        loading: false,
        switch: function(){
            this.on = !this.on;
        },
        send: function(sendFn){
            let self = this;
            self.loading = true;
            //发送请求
            sendFn().then(function(res){
                self.switch();
                self.loading = false;
            },function(e){
                self.loading = false;
            });
        }
    }
}

export default {
    name: "ui-treeworkspace",
    metaInfo: {
        title: "智能风控平台 - 打分卡"
    },
    components: {
        VJstree,
        ToolDengYu,
        ToolDateZaoYu,
        ToolStringContains,
        ToolDaYu,
        "score-action": ScoreAction,
        "indicator-shortcut": IndicatorShortcut
    },
    data: () => ({
        alertLevelList: [
            '请选择',
            '高',
            '中',
            '低'
        ],
        //预警规则名称编辑
        titleEdit: new TextEdit(),
        //节点名编辑
        nodeTitleEdit: new TextEdit(),
        //指标项全局变量
        title: '预警规则名称',
        showTxt: false,
        pid: null, //指标项ID
        allCardState: "arrow-shrink", //数据下探卡片收缩状态
        activeTab: "workspace", //当前选中的Tab值
        //左侧数据源列表
        apiMasterRelationList: [],
        //左侧数据源卡片列表
        apiCardList: [],
        globalConst: CONST,

        //工具列表
        toolList: [],

        // 新增下探数据的弹框对象
        apiCardModal: {
            show: false, //是否显示
            table: {
                columns: [
                    {
                        type: "selection",
                        width: 60,
                        align: "center"
                    },
                    {
                        title: "接口别名",
                        key: "aliasName"
                    }
                ],
                data: []
            }
        },

        //判定工具的视图工具
        decideNodeViewMap: {
            data: []
        },

        //判定工具的工作区
        decideWorkspace: {
            choiseTree: "", //选中的节点
            choiseTool: "", //选中的工具
            toolComponent: "", //工具的操作控件
            trueAction: {
                classData: { scoreAdj: 0 },
                actionType: "NoAction",
                alertLevel: '低'
            }, //判定为真的处理方式
            falseAction: {
                classData: { scoreAdj: 0 },
                actionType: "NoAction",
                alertLevel: '低'
            }, //判定为假的处理方式
            name: "判定节点名称" //判定卡片名称
        },

        // 判定处理的选项集合
        actions: [
            {
                text: "无动作",
                value: "NoAction"
            },
            {
                text: "执行操作",
                value: "Action"
            },
            {
                text: "链接子判定",
                value: "LinkNode"
            }
        ],

        // 判定工具列表
        toolComponentList: {
            gt: ToolDaYu, //大于
            lt: null, //小于
            eq: ToolDengYu, //等于
            neq: null, //不等于
            contains: ToolStringContains, //包含
            between: null, //区间
            monthBefore: ToolDateZaoYu //日期早于
        }
    }),
    // 实时监听变化
    computed: {
        showTrueShortcut: function() {
            return this.decideWorkspace.trueAction.actionType === "LinkNode";
        },
        showFalseShortcut: function() {
            return this.decideWorkspace.falseAction.actionType === "LinkNode";
        }
    },
    methods: {
        headerFocusFn(){
            console.log(112311);
        },
        updateTitle(){
            let self = this;
            return new Promise(function(resolve,reject){
                self.$http
                .get(
                    "/app/v1/determinationTools/types/demo"
                )
                .then(function(res) {
                    resolve(res);
                },function(res){
                    reject(res);
                });
            })
        },
        // 根据选中对象属性的类型，加载判定工具
        reloadToolList(choiseTree) {
            // console.log("reloadToolList choiseTree", choiseTree);
            let self = this;
            self.$http
                .get(
                    "/app/v1/determinationTools/types/" +
                        choiseTree.fieldType
                )
                .then(function(res) {
                    self.toolList = res.data;
                });
        },
        //切换Tab
        reloadActiveTabData(node) {
            let self = this;
            // console.log("reloadActiveTabData view tree params", node.data);
            if (self.activeTab === "workspace") {
                //重新加载工作区
                self.$http
                    .get(
                        "/app/v1/sketchpads/" +
                            self.pid +
                            "/nodes/" +
                            node.data.oid
                    )
                    .then(function(res) {
                        // console.log('reloadActiveTabData workspace',res.data);
                        let respData = res.data;
                        let trueActionClassData = JSON.parse(
                            respData.leftNodeAction.classData
                        );
                        let falseActionClassData = JSON.parse(
                            respData.rightNodeAction.classData
                        );

                        self.decideWorkspace = {
                            choiseTree: respData.apiResultDict, //选中的节点
                            choiseTreeApiPath:
                                respData.indicatorApiMasterRelation.apiPath, //左侧节点
                            choiseTool: respData.determinationTool, //选中的工具
                            toolComponent: "", //工具的操作控件
                            trueAction: {
                                actionType: respData.leftNodeAction.actionType,
                                classData: {
                                    scoreAdj: trueActionClassData
                                        ? parseInt(trueActionClassData.scoreAdj)
                                        : 0
                                }
                            }, //判定为真的处理方式
                            falseAction: {
                                actionType: respData.rightNodeAction.actionType,
                                classData: {
                                    scoreAdj: falseActionClassData
                                        ? parseInt(
                                              falseActionClassData.scoreAdj
                                          )
                                        : 0
                                }
                            }, //判定为假的处理方式
                            name: respData.nodeName, //判定卡片名称
                            determinationData: respData.determinationData
                        };

                        // console.log(
                        //     "reloadActiveTabData reuslt",
                        //     self.decideWorkspace
                        // );

                        self.reloadToolList(self.decideWorkspace.choiseTree);
                    });
            } else {
                //重新加载视图
            }
        },
        // 根据字段类型加载工具列表

        // 加载判定节点视图的数据
        loadNodeView() {
            let self = this;
            self.$http
                .get(
                    "/app/v1/sketchpads/" +
                        self.pid +
                        "/determineNodeRelation"
                )
                .then(function(res) {
                    self.decideNodeViewMap.data = res.data;
                    //构建思维导图的视图
                    self.buildMap();
                });
        },
        // 加载下探数据卡片的数据
        loadApiCardTree(apiCard) {
            let self = this,
                oid = apiCard.apiMasterOid;

            // console.log('loadApiCardTree come in',apiCard.aliasName,apiCard.oid);
            self.$http
                .get(
                    "/app/v1/sketchpads/apiRelations/" +
                        apiCard.oid +
                        "/resultDict"
                )
                .then(function(res) {
                    let respTreeData = res.data;
                    //遍历数组，手动set到数组中，否则Vue不会加入绑定监听
                    for (let i = 0; i < self.apiCardList.length; i++) {
                        let targetApiCard = self.apiCardList[i];
                        if (targetApiCard.oid === apiCard.oid) {
                            targetApiCard.treeDataList = respTreeData;
                            Vue.set(self.apiCardList, i, targetApiCard);
                            return false;
                        }
                    }
                });
        },
        // 视图切换到工作区
        nodeSelectionChanged(node) {
            // console.log("nodeSelectionChanged", node);
            this.activeTab = "workspace";
            this.reloadActiveTabData(node);
        },
        buildMap() {
            let self = this;
            myDiagram = $(
                go.Diagram,
                "myDiagramDiv", // must be the ID or reference to div
                {
                    "toolManager.hoverDelay": 100, // 100 milliseconds instead of the default 850
                    allowCopy: false,
                    // create a TreeLayout for the family tree
                    layout: $(go.TreeLayout, {
                        angle: 90,
                        nodeSpacing: 10,
                        layerSpacing: 40,
                        layerStyle: go.TreeLayout.LayerUniform
                    })
                }
            );

            // Set up a Part as a legend, and place it directly on the diagram
            myDiagram.add(
                $(go.Part, "Table", {
                    position: new go.Point(-200, -20),
                    selectable: false
                })
            );

            // get tooltip text from the object's data
            function tooltipTextConverter(person) {
                var str = "";
                str += "Born: " + person.birthYear;
                if (person.deathYear !== undefined)
                    str += "\nDied: " + person.deathYear;
                if (person.reign !== undefined)
                    str += "\nReign: " + person.reign;
                return str;
            }

            // define tooltips for nodes
            var tooltiptemplate = $(
                go.Adornment,
                "Auto",
                $(go.Shape, "Rectangle", {
                    fill: "whitesmoke",
                    stroke: "black"
                }),
                $(
                    go.TextBlock,
                    {
                        font: "bold 8pt Helvetica, bold Arial, sans-serif",
                        wrap: go.TextBlock.WrapFit,
                        margin: 5
                    },
                    new go.Binding("text", "", tooltipTextConverter)
                )
            );

            // define Converters to be used for Bindings
            function genderBrushConverter(actionType) {
                if (actionType === "LinkNode") return bluegrad;
                if (actionType === "NoAction") return graygrad;
                if (actionType === "Action") return pinkgrad;
                return "orange";
            }

            // replace the default Node template in the nodeTemplateMap
            myDiagram.nodeTemplate = $(
                go.Node,
                "Auto",
                {
                    deletable: false,
                    toolTip: tooltiptemplate,
                    selectionChanged: self.nodeSelectionChanged
                },
                new go.Binding("text", "name"),
                $(
                    go.Shape,
                    "Rectangle",
                    {
                        fill: "lightgray",
                        stroke: null,
                        strokeWidth: 0,
                        stretch: go.GraphObject.Fill,
                        alignment: go.Spot.Center
                    },
                    new go.Binding("fill", "actionType", genderBrushConverter)
                ),
                $(
                    go.TextBlock,
                    {
                        font: "700 12px Droid Serif, sans-serif",
                        textAlign: "center",
                        margin: 10,
                        maxSize: new go.Size(80, NaN)
                    },
                    new go.Binding("text", "name")
                )
            );

            // define the Link template
            myDiagram.linkTemplate = $(
                go.Link, // the whole link panel
                { routing: go.Link.Orthogonal, corner: 5, selectable: false },
                $(go.Shape, { strokeWidth: 3, stroke: "#424242" })
            ); // the gray link shape
            // create the model for the family tree
            myDiagram.model = new go.TreeModel(self.decideNodeViewMap.data);
        },
        //选中左侧数据源节点
        itemClick(node) {
            console.log(node.model);
            let self = this;
            self.activeTab = "wrokspace";
            self.decideWorkspace.choiseTree = {
                fieldName: node.model.fieldName,
                fieldType: node.model.fieldType,
                pathName: node.model.pathName
            };
            self.decideWorkspace.choiseTreeApiPath = node.model.apiPath;
        },
        //加载左侧数据源列表
        loadIndicatorsRelation() {
            let self = this;
            let url =
                "/app/v1/sketchpads/" +
                this.pid +
                "/apiMasterRelation";

            self.$http.get(url+"?pageSize="+1000).then(res => {
                // console.log(res.data);
                // 赋值
                self.apiMasterRelationList = res.data;
                // 解析
                self.parseIndicatorsRelationList(res.data);
            });
        },
        //解析
        parseIndicatorsRelationList(dataList) {
            let self = this;
            dataList.forEach(function(item, key, arr) {
                let indentNum = item.level === 3 ? 5 : item.level * 2;
                let apiCard = Object.assign(item, {
                    indentClass: "ml-" + indentNum,
                    isBase: item.parentApiMasterOid === 0,
                    baseClass:
                        item.parentApiMasterOid === 0
                            ? "border-secondary border-dashed"
                            : "",
                    treeLoaded: false,
                    treeDataList: [],
                    editer: new TextEdit()
                });
                //预先加载主体的数据
                if (apiCard.isBase) {
                    self.loadApiCardTree(apiCard);
                }
                self.apiCardList.push(apiCard);
                if (item.childList) {
                    self.parseIndicatorsRelationList(item.childList);
                }
            });
        },
        searchCard() {},
        addCard(oid) {
            this.apiCardModal.show = true;
            this.loadApiRelation(oid);
        },
        allCardTouch() {
            this.allCardState =
                this.allCardState === "arrow-shrink"
                    ? "arrow-expand"
                    : "arrow-shrink";
            if (this.allCardState === "arrow-shrink") {
                this.$Message.info("展开所有卡片");
            } else {
                this.$Message.info("收缩所有卡片");
            }
        },
        removeCard(apiCard) {
            this.$Modal.confirm({
                title: "系统提示",
                content: "<p>确认删除“" + apiCard.aliasName + "”下探？</p>",
                onOk: () => {
                    this.$Message.success("删除成功!");
                },
                onCancel: () => {
                    this.$Message.info("取消删除");
                }
            });
        },
        // 加载指定oid的数据源下探列表
        loadApiRelation(oid) {
            let self = this;
            let url =
                "/app/v1/apis/" + oid + "/relations?pageSize="+1000;
            self.$http.get(url).then(res => {
                // console.log(res.data);
                let respData = res.data;
            });
        },

        //修改数据下探卡片名称
        openAliasNameEdit(card,i) {
            let self = this;

            card.editer.on = true;
            let newCard = card;

            Vue.set(self.apiCardList,i,newCard);
        },
        //执行修改
        updateAliasName(card,i){
            let self = this;

            card.editer.on = false;
            let newCard = card;

            self.$http.get(
                "/app/v1/determinationTools/types/demo?pageSize="+1000
            )
            .then(function(res) {
                Vue.set(self.apiCardList,i,newCard);
            },function(res){
                console.log(res);
            });
        }
    },
    created() {
        let self = this;

        self.EventOperator.$on("rpcToolClick", function(tool) {
            // 选中的工具
            self.decideWorkspace.choiseTool = tool;
        });

        self.EventOperator.$on("rpcActionChange", function(change) {
            this[change.targe] = change.value;
        });
    },
    mounted() {
        //获取预警规则id
        this.pid = this.$route.query.pid;
        //加载基本源信息树结构
        this.loadIndicatorsRelation();
        //
        this.loadNodeView();
    }
};
</script>
